package org.arch_learn.rpc.nz_rpc.proxy;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.curator.framework.CuratorFramework;
import org.arch_learn.rpc.nz_rpc.common.RpcRequest;
import org.arch_learn.rpc.nz_rpc.common.RpcResponse;
import org.arch_learn.rpc.nz_rpc.endpoint.NettyRpcClient;
import org.joda.time.Duration;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 客户端代理类--创建代理对象
 * 1.封装request请求对象
 * 2.创建RpcClient对象
 * 3.发送消息
 * 4.返回结果
 */
public class NettyRpcClientProxy {
    private ConcurrentHashMap<String, List<NettyRpcClient>> nettyRpcClientMap;
    private CuratorFramework curatorFramework;


    public NettyRpcClientProxy(ConcurrentHashMap<String, List<NettyRpcClient>> nettyRpcClientMap,
                               CuratorFramework curatorFramework) {
        this.nettyRpcClientMap = nettyRpcClientMap;
        this.curatorFramework = curatorFramework;
    }

    public Object createProxy(Class serviceClass) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        System.out.println("==========执行NettyRpcClientProxy.invoke()方法，执行代理");
                        //1.
                        RpcRequest rpcRequest = new RpcRequest();
                        rpcRequest.setRequestId(UUID.randomUUID().toString());
                        rpcRequest.setClassName(method.getDeclaringClass().getName());
                        rpcRequest.setParameterTypes(method.getParameterTypes());
                        rpcRequest.setMethodName(method.getName());
                        rpcRequest.setParameters(args);
                        //2.
                        NettyRpcClient rpcClient = null;
                        try {
                            //3.
                            String interfaceName = method.getDeclaringClass().getName();
                            //选择响应时间短的
                            rpcClient = chooseFast(nettyRpcClientMap, interfaceName);

                            //重连，防止持有的客户端是断连的。
                            rpcClient.reconnect();

                            Date requestDate = new Date();
                            Object resultMessage = rpcClient.send(JSONObject.toJSONString(rpcRequest));
                            Date receiveDate = new Date();

                            //刷新服务调用时刻和花费时间到相应节点的内容里
                            logRequestInfoToZookeeper(requestDate, receiveDate, interfaceName, rpcClient.getConnectStr());

                            RpcResponse rpcResponse = JSONObject.parseObject(resultMessage.toString(), RpcResponse.class);
                            if (rpcResponse.getError() != null) {
                                throw new RuntimeException(rpcResponse.getError());
                            }
                            //4.
                            Object result = rpcResponse.getResult();
                            Type returnType = method.getReturnType();

                            return JSON.parseObject(result.toString(), returnType);
                        } catch (Exception e) {
                            throw e;
                        }
                    }
                }
        );
    }

    private void logRequestInfoToZookeeper(Date requestDate, Date receiveDate, String interfaceName, String connectStr) throws Exception {
        long millis = new Duration(requestDate.getTime(), receiveDate.getTime()).getMillis();
        curatorFramework.setData().forPath("/" + interfaceName + "/" + connectStr, (requestDate.getTime() + " " + millis).getBytes());
    }

    private NettyRpcClient chooseFast(ConcurrentHashMap<String, List<NettyRpcClient>> nettyRpcClientMap, String interfaceName) throws Exception {
        List<NettyRpcClient> nettyRpcClients = nettyRpcClientMap.get(interfaceName);
        if (nettyRpcClients == null || nettyRpcClients.size() == 0)
            throw new RuntimeException("no available services provided!");
        List<String> children = curatorFramework.getChildren().forPath("/" + interfaceName);
        HashMap<String, ArrayList<String>> map = new HashMap<>();
        Long shorTestDuration = Long.MAX_VALUE;
        for (int i = 0; i < children.size(); i++) {
            String path = "/" + interfaceName + "/" + children.get(i);
            byte[] bytes = curatorFramework.getData().forPath(path);
            if (null != bytes) {
                String info = new String(bytes);
                String durationStr = info.split(" ")[1];
                Long duration = Long.valueOf(durationStr);
                shorTestDuration = Long.min(shorTestDuration, duration);
                ArrayList<String> strings = map.get(shorTestDuration.toString());
                if (strings == null || strings.size() == 0) {
                    map.put(shorTestDuration.toString(), new ArrayList(Collections.singleton(children.get(i))));
                } else {
                    strings.add(children.get(i));
                }
            } else {
                ArrayList<String> strings = map.get(new Long(0).toString());
                if (strings == null || strings.size() == 0) {
                    map.put(new Long(0).toString(), new ArrayList(Collections.singleton(children.get(i))));
                } else {
                    strings.add(children.get(i));
                    map.put(new Long(0).toString(), strings);
                }
            }
        }
        String key = map.keySet().stream()
                .min(Comparator.comparing(k -> Long.valueOf(k)))
                .get();
        List<String> strings = map.get(key);
        int i = new Random().nextInt(strings.size());
        i = i != 0 ? i - 1 : i;
        String connectStr = strings.get(i);
        return nettyRpcClients.stream().filter(n -> connectStr.equals(n.getConnectStr()))
                .findFirst().get();
    }
}
